package com.abing.api.task;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.abing.api.cache.ApiCache;
import com.abing.api.config.StarryApiConfig;
import com.abing.api.model.BaseResponse;
import com.abing.api.model.InterfaceInfoEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author CaptainBing
 * @Date 2024/8/23 16:24
 * @Description
 */
@Slf4j
//@Component
@RequiredArgsConstructor
public class InitApiCache implements CommandLineRunner {

    private final StarryApiConfig starryApiConfig;

    private final ApiCache interfaceCache;
    @Override
    public void run(String... args) throws Exception {

        log.info("init api cache:{}",starryApiConfig);
        String body = HttpRequest.of(starryApiConfig.getInitUrl())
                                 .method(Method.GET)
                                 .execute()
                                 .body();
        BaseResponse baseResponse = JSONUtil.toBean(body, BaseResponse.class);
        if (baseResponse.getCode() != HttpStatus.HTTP_OK){
            log.error("init api cache fail,code:{},message:{}", baseResponse.getCode(),baseResponse.getMessage());
            return;
        }
        Map<String, InterfaceInfoEntity> interfaceMap = baseResponse.getData()
                                                                    .stream()
                                                                    .collect(Collectors.toMap(InterfaceInfoEntity::getId, e -> e));
        interfaceCache.set(interfaceMap);
    }
}
